#文件读取
f = open("demo.txt", "r")
print(f.read())
#输出：hello world!

#文件读取
f = open("demo.txt", "r")
print(f.read())
#输出：hello world!

#读取中文
f = open("chinese.txt", "r", encoding='utf-8')
print(f.read())
#输出：你好呀！

#默认情况下，read() 方法返回整个文本，但您也可以指定要返回的字符数：
f = open("demo.txt", "r")
print(f.read(5))
#输出：hello

#您可以使用 readline() 方法返回一行：
f = open("demo.txt", "r")
print(f.readline())
#输出：hello world!

#逐行遍历文件
f = open("demo.txt", "r")
for x in f:
  print(x)

#关闭文件
f = open("demo.txt", "r")
print(f.readline())
f.close()

#文件追加
f = open("demo2.txt", "a")
f.write(" append dog!")
f.close()

# 追加后，打开并读取该文件：
f = open("demo2.txt", "r")
print(f.read())
#输出：hello world! xiaomingappend dog! append dog!

#覆盖
f = open("demo3.txt", "w")
f.write("I have deleted the content!")
f.close()

# 写入后，打开并读取该文件：
f = open("demo3.txt", "r")
print(f.read())
#输出：I have deleted the content!

#创建名为 "myfile.txt" 的文件：
f = open("myfile.txt", "x")

#如果不存在，则创建新文件：
f = open("myfile.txt", "w")